package ws

import (
	"encoding/json"
	"ims/app/dao"
	"regexp"
	"strings"

	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
	"github.com/gorilla/websocket"
)

func ReciveChatMessage(message *Message) error {
	var typeMsg TypeMessage
	json.Unmarshal(message.content, &typeMsg)

	td := gjson.New(typeMsg.Data)
	//当前发来消息的人在服务器上ChatRoom里面的数据
	wsconn := CurrentWsconn(message)
	if wsconn == nil {
		return gerror.New("用户不存在")
	}

	g.Log().Debug("收到聊天消息:", typeMsg.Data)

	to_user_id := gconv.Int(td.Get("to_user_id"))
	//测试用，如果是客服发来消息指定给某个访客
	// if wsconn.Type == "kefu" {
	// 	to_user_id = 861
	// }

	//msg_type  1=文字 2=表情 3=图片 4=语音 5 = 商品链接 6 = 订单类型
	msn_type := gconv.Int(td.Get("type"))
	msn := gconv.String(td.Get("msn"))

	msn = trimHtml(msn)

	userId := wsconn.UserId
	appid := wsconn.Appid
	// other:= td.Get("other")
	guid := td.Get("guid")
	if wsconn.ToUserID == 0 {
		// log.Println("")
		return gerror.New("用户不存在")
	}
	if to_user_id == userId {
		// log.Println("")
		return gerror.New("不能和自己聊天")
	}
	data := map[string]interface{}{
		"to_user_id": to_user_id,
		"msn_type":   msn_type,
		"msn":        msn,
		"add_time":   gtime.Timestamp(),
		"appid":      appid,
		"user_id":    userId,
		"guid":       gconv.Int(guid),
		"is_send":    1,
	}
	g.Log().Debug(data)
	toUserInfo := dao.GetChatUserInfoById(to_user_id)
	toUserWsconn := ChatRoom[gconv.String(toUserInfo.Uid)]
	//var toUserPingInfo *PingInfo

	data["type"] = 1
	if toUserWsconn != nil && toUserWsconn.ToUserID == userId {
		data["type"] = 1
	}

	data["id"], _ = dao.ChatDialogueRecord.M.InsertAndGetId(data)

	unMessageCount := dao.GetUnMessageCount(appid, userId, to_user_id)
	recored := dao.SaveChatRecord(
		appid,
		userId,
		to_user_id,
		gconv.String(msn),
		0,
		msn_type,
		unMessageCount,
		0,
		wsconn.Nickname,
		wsconn.Avatar,
		1)

	data["create_time"] = gtime.New(recored.AddTime).String()
	data["update_time"] = gtime.New(recored.UpdateTime).String()

	data["avatar"] = wsconn.Avatar
	data["nickname"] = wsconn.Nickname
	//如果to_user 在线，给接收消息的聊天对象例如 客服，发ws消息
	if toUserWsconn != nil {

		data["recored"] = recored
		// data["avatar"] = toUserWsconn.Avatar
		// data["nickname"] = toUserWsconn.Nickname
		g.Log().Debug(" toUserChat 数据", data)

		PushingMessage(toUserWsconn.Conn, "chat", data)
	}

	//重新获取我的聊天消息列表
	data["recored"] = dao.GetChatRecord(appid, userId, to_user_id)

	//给我发送ws消息
	PushingMessage(wsconn.Conn, "chat", data)
	return nil
}

func trimHtml(src string) string {
	//将HTML标签全转换成小写
	re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
	src = re.ReplaceAllStringFunc(src, strings.ToLower)
	//去除STYLE
	re, _ = regexp.Compile("\\<style[\\S\\s]+?\\</style\\>")
	src = re.ReplaceAllString(src, "")
	//去除SCRIPT
	re, _ = regexp.Compile("\\<script[\\S\\s]+?\\</script\\>")
	src = re.ReplaceAllString(src, "")
	//去除所有尖括号内的HTML代码，并换成换行符
	re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
	src = re.ReplaceAllString(src, "\n")
	//去除连续的换行符
	re, _ = regexp.Compile("\\s{2,}")
	src = re.ReplaceAllString(src, "\n")
	return strings.TrimSpace(src)
}

func ReciveUserMessage(message *Message) {
	var typeMsg TypeMessage
	json.Unmarshal(message.content, &typeMsg)

	td := gjson.New(typeMsg.Data)

	msgData, _ := json.Marshal(typeMsg.Data)

	var clientUser ClientUser
	gconv.Struct(msgData, &clientUser)
	clientUser.Type = "user"
	//防止ajax提交过来的uid 是数字类型转字符串
	clientUser.UID = gconv.String(td.Get("uid"))

	g.Log().Debug("此用户登录了:", clientUser)
	//查询数据库获取 用户
	chatUser := dao.GetChatUserInfo(gconv.Int(clientUser.UID))

	data := make(map[string]interface{})
	data["user_id"] = chatUser.Id
	data["recored"] = make(map[string]string)
	data["num"] = 0
	g.Log().Debug("客户端ws:", clientUser.UID)
	//加入到 聊天的room
	//用户id对应的连接
	user := &Wsconn{
		Conn:     message.conn,
		Now:      gtime.Timestamp(),
		Appid:    APPID,
		Avatar:   clientUser.Avatar,
		ToUserID: clientUser.ToUserID,
		UID:      clientUser.UID,
		Type:     clientUser.Type,
		Nickname: clientUser.Nickname,
		UserId:   chatUser.Id,
	}
	ChatRoom[clientUser.UID] = user

	msg := TypeMessage{
		Type:   "mssage_num",
		Data:   data,
		Status: 200,
	}
	str, _ := json.Marshal(msg)
	Mux.Lock()
	message.conn.WriteMessage(websocket.TextMessage, str)
	Mux.Unlock()
}

// 处理客户端消息ping
func PingHander(message *Message) {
	var user PingInfo
	for uid := range ChatRoom {
		if ChatRoom[uid].Conn == message.conn {
			gconv.Struct(ChatRoom[uid], &user)
			//更新最后ping的时间
			ChatRoom[uid].Now = gtime.Timestamp()
		}
	}

	msg := TypeMessage{
		Type: "ping",
		Data: &PingData{
			Now:  gtime.Timestamp(),
			Info: user,
		},
		Status: 200,
	}
	str, _ := json.Marshal(msg)
	Mux.Lock()
	message.conn.WriteMessage(websocket.TextMessage, str)
	Mux.Unlock()
}
